const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  const { studyRecordId, action, matchId } = event || {};
  
  console.log('getStudyRecord 函数调用，参数:', {
    userId,
    studyRecordId,
    event,
    eventKeys: Object.keys(event || {}),
    studyRecordIdType: typeof studyRecordId
  });
  
  if (!userId) {
    return {
      code: 1,
      message: '用户未登录'
    };
  }
  
  // 确保studyRecordId不是userId
  if (studyRecordId === userId) {
    console.error('错误：studyRecordId与userId相同，可能存在参数混淆');
    return {
      code: 400,
      message: '参数错误：学习记录ID不能与用户ID相同',
      error: `studyRecordId (${studyRecordId}) 与 userId (${userId}) 相同`
    };
  }
  
  try {
    // action 路由：根据 matchId 查询对端资料（临时合并逻辑）
    if (action === 'peerByMatchId') {
      try {
        console.log('action=peerByMatchId, matchId:', matchId, 'userId:', userId);
        const rs = await db
          .collection('study_records')
          .where({
            matchId: matchId,
            userId: _.neq(userId)
          })
          .orderBy('createTime', 'desc')
          .limit(1)
          .get();

        if (!rs.data || rs.data.length === 0) {
          return { code: 404, message: '未找到对端学习记录', data: null };
        }

        const peerRecord = rs.data[0];
        const peerUserId =
          peerRecord.userId ||
          peerRecord._openid ||
          peerRecord.openid ||
          peerRecord.openId ||
          '';

        // 读取对端用户资料（默认占位）
        let partnerInfo = {
          nickName: '学习伙伴',
          avatarUrl: '/static/icons/avatar-placeholder.png'
        };

        if (peerUserId) {
          try {
            console.log('[peerByMatchId] peerUserId:', peerUserId);
            let ui = {};
            const ures = await db.collection('users').where({ _openid: peerUserId }).limit(1).get();
            const cnt = (ures && ures.data && ures.data.length) || 0;
            console.log('[peerByMatchId] users.where({_openid}) count:', cnt);
            if (cnt > 0) {
              ui = ures.data[0] || {};
            } else {
              // fallback: 尝试按 doc(peerUserId) 读取
              try {
                const udoc = await db.collection('users').doc(peerUserId).get();
                if (udoc && udoc.data) {
                  console.log('[peerByMatchId] users.doc fallback HIT');
                  ui = udoc.data;
                } else {
                  console.log('[peerByMatchId] users.doc fallback MISS');
                }
              } catch (e2) {
                console.log('[peerByMatchId] users.doc fallback ERROR:', e2 && (e2.message || e2));
              }
            }
            partnerInfo = {
              nickName: ui.nickName || ui.nickname || '学习伙伴',
              avatarUrl:
                ui.avatarUrl ||
                ui.avatar_url ||
                ui.avatar ||
                '/static/icons/avatar-placeholder.png'
            };
            console.log('[peerByMatchId] final partnerInfo:', partnerInfo);
          } catch (ue) {
            console.log('读取对端用户资料失败，使用默认占位:', ue && (ue.message || ue));
          }
        }

        // 如果头像是 cloud:// fileID，转成临时 https 链接
        try {
          if (
            partnerInfo &&
            typeof partnerInfo.avatarUrl === 'string' &&
            partnerInfo.avatarUrl.indexOf('cloud://') === 0
          ) {
            const tf = await cloud.getTempFileURL({ fileList: [partnerInfo.avatarUrl] });
            const list = (tf && tf.fileList) || [];
            if (list[0] && list[0].tempFileURL) {
              partnerInfo.avatarUrl = list[0].tempFileURL;
            }
          }
        } catch (te) {
          console.log('getTempFileURL 失败，使用原始 avatarUrl:', te && (te.message || te));
        }

        return {
          code: 0,
          message: 'ok',
          data: {
            peerStudyRecord: {
              _id: peerRecord._id,
              userId: peerUserId,
              matchId: matchId
            },
            partnerInfo
          }
        };
      } catch (actionErr) {
        console.error('peerByMatchId 分支失败:', actionErr);
        return { code: 500, message: '服务器错误', error: actionErr.message || String(actionErr) };
      }
    }

    let studyRecord;
    
    // 如果提供了studyRecordId，查询特定记录
    if (studyRecordId) {
      // 检查studyRecordId是否有效
      if (studyRecordId === 'null' || studyRecordId === 'undefined') {
        return {
          code: 400,
          message: '无效的学习记录ID',
          error: `提供的ID值无效: ${studyRecordId}`
        };
      }
      
      // 再次确认studyRecordId的值
      console.log(`准备查询学习记录，确认参数 - studyRecordId: ${studyRecordId}, userId: ${userId}`);
      
      try {
        console.log(`尝试查询学习记录，确认参数 - studyRecordId: ${studyRecordId}, userId: ${userId}`);
        console.log(`studyRecordId类型: ${typeof studyRecordId}, 长度: ${studyRecordId ? studyRecordId.length : 'undefined'}`);
        
        // 再次确认我们使用的是正确的ID
        if (!studyRecordId || studyRecordId === userId) {
          console.error(`参数错误 - studyRecordId: ${studyRecordId}, userId: ${userId}`);
          return {
            code: 400,
            message: '参数错误：学习记录ID无效',
            error: `studyRecordId (${studyRecordId}) 无效或与userId相同`
          };
        }
        
        console.log(`开始查询学习记录，使用ID: ${studyRecordId}`);
        
        // 直接使用doc查询
        const result = await db.collection('study_records').doc(studyRecordId).get();
        
        if (!result.data) {
          console.log(`学习记录不存在，ID: ${studyRecordId}`);
          return {
            code: 404,
            message: '学习记录不存在',
            data: null
          };
        }
        
        console.log(`找到学习记录: ${JSON.stringify(result.data)}`);
        
        // 验证记录是否属于当前用户（如果记录中有userId字段）
        if (result.data.userId && result.data.userId !== userId) {
          console.log(`权限验证失败: 记录用户ID ${result.data.userId} 不匹配当前用户ID ${userId}`);
          return {
            code: 403,
            message: '无权访问此学习记录',
            data: null
          };
        }
        
        studyRecord = result.data;
      } catch (dbError) {
        console.error('数据库查询错误:', dbError);
        return {
          code: 500,
          message: '数据库查询错误',
          error: dbError.message
        };
      }
    } else {
    // 如果没有提供studyRecordId，查询用户最新的未开始学习记录
    console.log(`未提供studyRecordId，查询用户${userId}最新的学习记录`);
    const studyRecords = await db.collection('study_records').where({
      userId: userId,
      status: _.in(['not_started', 'started'])
    }).orderBy('createTime', 'desc').limit(1).get();
      
      if (!studyRecords.data || studyRecords.data.length === 0) {
        return {
          code: 404,
          message: '没有找到学习记录',
          data: null
        };
      }
      
      studyRecord = studyRecords.data[0];
    }
    
    // 获取用户信息
    let userInfo = {};
    try {
      const userResult = await db.collection('users').doc(userId).get();
      userInfo = userResult.data || {};
    } catch (userError) {
      console.log('获取用户信息失败，使用默认值:', userError.message);
      userInfo = {};
    }
    
    // 通过 matchId 查询对端记录，再到 users 获取对方昵称与头像（不再依赖 studyRecord.partnerInfo / partnerId）
    let partnerInfo = {
      nickName: '学习伙伴',
      avatarUrl: '/static/icons/avatar-placeholder.png'
    };
    try {
      if (studyRecord.matchId) {
        const prs = await db.collection('study_records')
          .where({
            matchId: studyRecord.matchId,
            userId: _.neq(userId)
          })
          .orderBy('createTime', 'desc')
          .limit(1)
          .get();
        if (prs && prs.data && prs.data[0]) {
          const peerRecord = prs.data[0];
          const peerUserId =
            peerRecord.userId ||
            peerRecord._openid ||
            peerRecord.openid ||
            peerRecord.openId ||
            '';
          if (peerUserId) {
            try {
              console.log('[main] peerUserId:', peerUserId);
              let ui = {};
              const ures = await db.collection('users').where({ _openid: peerUserId }).limit(1).get();
              const cnt = (ures && ures.data && ures.data.length) || 0;
              console.log('[main] users.where({_openid}) count:', cnt);
              if (cnt > 0) {
                ui = ures.data[0] || {};
              } else {
                // fallback: 尝试按 doc(peerUserId) 读取
                try {
                  const udoc = await db.collection('users').doc(peerUserId).get();
                  if (udoc && udoc.data) {
                    console.log('[main] users.doc fallback HIT');
                    ui = udoc.data;
                  } else {
                    console.log('[main] users.doc fallback MISS');
                  }
                } catch (e2) {
                  console.log('[main] users.doc fallback ERROR:', e2 && (e2.message || e2));
                }
              }
              partnerInfo.nickName = ui.nickName || ui.nickname || partnerInfo.nickName;
              partnerInfo.avatarUrl =
                ui.avatarUrl || ui.avatar_url || ui.avatar || partnerInfo.avatarUrl;
              console.log('[main] final partnerInfo:', partnerInfo);
            } catch (ue) {
              console.log('读取对端用户资料失败，使用默认占位:', ue && (ue.message || ue));
            }
          }
        }
      }
    } catch (pe) {
      console.log('通过 matchId 取对端资料失败:', pe && (pe.message || pe));
    }

    // 头像规范化：cloud:// 转临时 https；/assets 占位替换为 /static
    try {
      if (partnerInfo && typeof partnerInfo.avatarUrl === 'string') {
        if (partnerInfo.avatarUrl.indexOf('cloud://') === 0) {
          const tf = await cloud.getTempFileURL({ fileList: [partnerInfo.avatarUrl] });
          const list = (tf && tf.fileList) || [];
          if (list[0] && list[0].tempFileURL) {
            partnerInfo.avatarUrl = list[0].tempFileURL;
          }
        } else if (partnerInfo.avatarUrl.indexOf('/assets/') === 0) {
          partnerInfo.avatarUrl = '/static/icons/avatar-placeholder.png';
        }
      }
    } catch (te) {
      console.log('getTempFileURL 失败（主分支）:', te && (te.message || te));
    }
    
    return {
      code: 0,
      message: '获取学习记录成功',
      data: {
        _id: studyRecord._id,
        studyRecordId: studyRecord._id, // 保持兼容性
        userId: studyRecord.userId,
        matchId: studyRecord.matchId,
        startTime: studyRecord.startTime,
        endTime: studyRecord.endTime,
        duration: studyRecord.duration,
        status: studyRecord.status,
        partnerInfo: partnerInfo,
        userInfo: {
          nickName: userInfo.nickName || '我',
          avatarUrl: userInfo.avatarUrl || '/static/icons/avatar-placeholder.png'
        },
        createTime: studyRecord.createTime,
        updateTime: studyRecord.updateTime,
        actualStartTime: studyRecord.actualStartTime,
        actualEndTime: studyRecord.actualEndTime,
        actualDuration: studyRecord.actualDuration || 0,
        breakCount: studyRecord.breakCount || 0,
        focusScore: studyRecord.focusScore || 0
      }
    };
  } catch (error) {
    console.error('获取学习记录出错:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      studyRecordId,
      userId
    });
    
    // 提供更详细的错误信息
    let errorMessage = '服务器错误';
    let errorDetails = error.message;
    
    // 检查是否是文档不存在错误
    if (error.message && error.message.includes('does not exist')) {
      errorMessage = '学习记录不存在';
      errorDetails = `找不到ID为 ${studyRecordId} 的学习记录`;
    }
    
    return {
      code: 500,
      message: errorMessage,
      error: errorDetails
    };
  }
};
